package com.mission.schedule.activity

import android.app.Activity
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.onekeyshare.OnekeyShare
import com.android.volley.AuthFailureError
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.lidroid.xutils.HttpUtils
import com.lidroid.xutils.exception.HttpException
import com.lidroid.xutils.http.RequestParams
import com.lidroid.xutils.http.ResponseInfo
import com.lidroid.xutils.http.callback.RequestCallBack
import com.lidroid.xutils.http.client.HttpRequest
import com.mission.schedule.CommonDialog.NewSixTaskDetailDialog
import com.mission.schedule.R
import com.mission.schedule.applcation.App
import com.mission.schedule.bean.CalenderNoteBean
import com.mission.schedule.bean.CalenderNoteSynBean
import com.mission.schedule.bean.ClenderUrlBean
import com.mission.schedule.bean.DownNewSixTaskBean
import com.mission.schedule.bean.qd606.NoteTitleDetailBean
import com.mission.schedule.constants.ShareFile
import com.mission.schedule.constants.URLConstants
import com.mission.schedule.entity.ScheduleTable
import com.mission.schedule.service.DownImageService
import com.mission.schedule.service.LocalSynService
import com.mission.schedule.utils.*
import com.nostra13.universalimageloader.core.DisplayImageOptions
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener
import kotlinx.android.synthetic.main.activity_task_detail.*
import kotlinx.android.synthetic.main.dialog_noteedit_detail_item1.*
import kotlinx.android.synthetic.main.qdfx_de_list_item.view.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.*

class ZoneDetailActivity : Activity() {

    var title_img = ""
    var pname = ""
    var id = 0

    var times = ""
    var userid = ""
    var stylee = 0


    lateinit var share: SharedPrefUtil
    lateinit var context: Context
    lateinit var imageLoader: ImageLoader
    lateinit var animateFirstListener: ImageLoadingListener
    lateinit var options: DisplayImageOptions
    var list2: List<QDZoneDetailActivity.QDBean.ListBean> = listOf()
    var adapter = ChildAdapter()
    var titleId = ""
    var name = ""
    var uid = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_task_detail)

        context = this@ZoneDetailActivity
        imageLoader = ImageLoader.getInstance()
        animateFirstListener = AnimateFirstDisplayListener()

        share = SharedPrefUtil(context, ShareFile.USERFILE)

        userid = share.getString(ShareFile.USERID, "")
        times = intent.getStringExtra("time")
        name = intent.getStringExtra("name")
        title = intent.getStringExtra("title")
        id = intent.getIntExtra("id", 0)
        titleId = intent.getStringExtra("titleId")
        uid = intent.getStringExtra("uid")
        stylee = intent.getIntExtra("stylee", 0)
        title_img = intent.getStringExtra("imageUrl")
        var title_img = intent.getStringExtra("path")

        showTitleImage(title_img)

        recyclerview.layoutManager = LinearLayoutManager(context)
        recyclerview.adapter = adapter

        options = DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.b1)
                .showImageForEmptyUri(R.mipmap.b1)
                .showImageOnFail(R.mipmap.b1).cacheInMemory(true)
                .cacheOnDisc(true).cacheInMemory(true)
                .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                .build()


        setInit()

        loadData()

        top_ll_back.setOnClickListener {
            onBackPressed()
        }

    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    private fun setInit() {

        var time1 = times.substring(0, 10)

        time1 += "  全天"

        time1 += "  顺"

        val imageUrl = URLConstants.图片 + title_img + "&imageType=2&imageSizeType=3"

        time_type.text = time1
        time_type.textSize = 14f
        head_name.text = name
        head_name.textSize = 16f
        title_type.visibility = View.GONE
        ide.text = "云清单:#$id"
        ide.visibility = View.VISIBLE

        content.text = title
        create_time.text = "创建时间: ${times.replace('T', ' ')}"
        top_ll_right.visibility = View.GONE

        imageLoader.displayImage(imageUrl, head_img, options, animateFirstListener)
    }

    private fun showTitleImage(path: String?) {
        if (path != null) {
            if (path != "") {
                val options = DisplayImageOptions.Builder()
                        .showStubImage(R.mipmap.loads)          // 设置图片下载期间显示的图片
                        .showImageForEmptyUri(R.mipmap.loads)  // 设置图片Uri为空或是错误的时候显示的图片
                        .showImageOnFail(R.mipmap.loads)       // 设置图片加载或解码过程中发生错误显示的图片
                        .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                        .cacheOnDisc(true)                          // 设置下载的图片是否缓存在SD卡中
                        .build()
                val imageUrl = URLConstants.图片 + path + "&imageType=15&imageSizeType=1"
                ImageLoader.getInstance().displayImage(imageUrl, header_image, options)

                header_image.visibility = View.VISIBLE
            } else {
                header_image.visibility = View.GONE
            }
        } else {
            header_image.visibility = View.GONE
        }
    }

    private fun loadData() {
        var loaders = ProgressUtil()
        loaders.ShowProgress(context, true, true, "正在下载...")
        val request3 = object : StringRequest(Method.POST, URLConstants.我的空间清单子项查询, Response.Listener { s ->
            if (!TextUtils.isEmpty(s)) {
                try {
                    val goon = Gson()
                    val textBean = goon.fromJson(s, QDZoneDetailActivity.QDBean::class.java)
                    if (textBean.status == 0) {
                        list2 = textBean.list

                        if (list2.isNotEmpty()) {
                            Collections.sort(list2) { arg0, arg1 -> arg0.orderId.compareTo(arg1.orderId) }
                            adapter.notifyDataSetChanged()
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
            loaders.dismiss()
        }, Response.ErrorListener {
            loaders.dismiss()
        }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                map.put("uId", uid)
                map.put("titleId", titleId)
                return map
            }
        }
        request3.tag = "downSixTaskCalender"
        request3.retryPolicy = DefaultRetryPolicy(5000, 1, 1.0f)
        App.getHttpQueues().add(request3)
    }

    /**
     * 图片加载第一次显示监听器
     *
     * @author Administrator
     */
    private class AnimateFirstDisplayListener : SimpleImageLoadingListener() {

        override fun onLoadingComplete(imageUri: String, view: View?,
                                       loadedImage: Bitmap?) {
            if (loadedImage != null) {
                val imageView = view as ImageView?
                // 是否第一次显示
                val firstDisplay = !displayedImages.contains(imageUri)
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500)
                    displayedImages.add(imageUri)
                }
            }
        }

        companion object {

            internal val displayedImages: MutableList<String> = Collections.synchronizedList(LinkedList())
        }
    }

    inner class ChildAdapter : RecyclerView.Adapter<ChildAdapter.Holder>() {

        override fun getItemCount(): Int {
            return list2.size
        }

        override fun onBindViewHolder(holder: ChildAdapter.Holder, position: Int) {

            if (list2.isNotEmpty()) {
                when (stylee) {
                    0 -> {
                        holder.itemView.ll.visibility = View.VISIBLE
                        holder.itemView.ch.visibility = View.VISIBLE
                        if (list2[position].endstate == 0) {
                            holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_unfinish_c)
                        } else {
                            holder.itemView.ch.background = resources.getDrawable(R.mipmap.btn_qd_finish_c)
                        }
                        holder.itemView.dd.visibility = View.GONE
                        holder.itemView.xh.visibility = View.GONE
                        holder.itemView.santai.visibility = View.GONE
                    }
                    1 -> {
                        holder.itemView.ll.visibility = View.VISIBLE
                        holder.itemView.ch.visibility = View.GONE
                        holder.itemView.dd.visibility = View.VISIBLE
                        holder.itemView.xh.visibility = View.GONE
                        holder.itemView.santai.visibility = View.GONE
                    }
                    2 -> {
                        holder.itemView.ll.visibility = View.VISIBLE
                        holder.itemView.ch.visibility = View.GONE
                        holder.itemView.dd.visibility = View.GONE
                        holder.itemView.xh.visibility = View.VISIBLE
                        holder.itemView.santai.visibility = View.GONE
                    }
                    3 -> {
                        holder.itemView.ch.visibility = View.GONE
                        holder.itemView.dd.visibility = View.GONE
                        holder.itemView.xh.visibility = View.GONE
                        holder.itemView.ll.visibility = View.GONE
                        holder.itemView.santai.visibility = View.GONE
                        holder.itemView.emty_v.visibility = View.VISIBLE
                    }
                    4 -> {
                        holder.itemView.ch.visibility = View.GONE
                        holder.itemView.dd.visibility = View.GONE
                        holder.itemView.xh.visibility = View.GONE
                        holder.itemView.ll.visibility = View.VISIBLE
                        holder.itemView.santai.visibility = View.VISIBLE
                        when {
                            list2[position].endstate == 0 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai1)
                            list2[position].endstate == 1 -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai2)
                            else -> holder.itemView.santai.background = resources.getDrawable(R.mipmap.icon_santai3)
                        }
                    }
                }

                setcolor(list2[position].contents, holder.itemView.content_tv)
                holder.itemView.xh.text = "${position + 1}."

                val style = SpannableStringBuilder(list2[position].contents)
                var remark4 = list2[position].remark4
                if (remark4 == "" || remark4 == null) {
                    remark4 = "0"
                }
                val color = Integer.valueOf(remark4)
                if (color > 0) {
                    style.setSpan(BackgroundColorSpan(context.resources.getColor(colorss[color])), 0, list2[position].contents!!.length,
                            Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
                    if (color > 2) {
                        style.setSpan(ForegroundColorSpan(Color.WHITE), 0, list2[position].contents!!.length,
                                Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
                    }
                    holder.itemView.content_tv.text = style
                    holder.itemView.content_tv.setLineSpacing(1f, 1f)
                }
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildAdapter.Holder {
            val view = LayoutInflater.from(this@ZoneDetailActivity).inflate(R.layout.calender_taskfx_de_list_item, parent, false)
            return Holder(view)
        }


        inner class Holder(itemview: View) : RecyclerView.ViewHolder(itemview)

    }
    var colorss = intArrayOf(R.color.white, R.color.color_m_1, R.color.color_m_2, R.color.color_m_3, R.color.color_m_4, R.color.color_m_5)

    //设置双#号包裹的文字颜色
    private fun setcolor(content: String, editText: TextView) {
        if (content.length > 1) {
            val builder = SpannableStringBuilder(content)
            val integerList = ArrayList<Int>()
            var index = 0
            val count = hit(content, "#")
            if (count > 1) {
                if (count % 2 == 0) {
                    for (i in 0 until count) {
                        if (i == 0) {
                            index = content.indexOf("#")
                        } else {
                            index = content.indexOf("#", index + 1)
                        }
                        integerList.add(index)
                    }
                    for (i in integerList.indices) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                val span = ForegroundColorSpan(Color.parseColor("#df7926"))
                                builder.setSpan(span, integerList[i - 1], integerList[i] + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
                            }
                        }
                    }
                    editText.text = builder
                } else {
                    for (i in 0 until count - 1) {
                        if (i == 0) {
                            index = content.indexOf("#")
                        } else {
                            index = content.indexOf("#", index + 1)
                        }
                        integerList.add(index)

                    }
                    for (i in integerList.indices) {
                        if (i > 0) {
                            if (i % 2 != 0) {
                                val span = ForegroundColorSpan(Color.parseColor("#df7926"))
                                builder.setSpan(span, integerList[i - 1], integerList[i] + 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
                            }
                        }
                    }
                    editText.text = builder
                }
            } else {
                editText.text = content
            }
        } else {
            editText.text = content
        }
        editText.setLineSpacing(20f, 1.5f)
    }

    /**
     * @param a 被匹配的长字符串
     * @param b 匹配的短字符串
     * @return 匹配次数
     */
    fun hit(a: String, b: String): Int {
        if (a.length < b.length) {
            return 0
        }
        val a_t = a.toCharArray()
        var count = 0

        for (i in 0 until a.length) {
            val buffer = StringBuffer()
            for (j in 0 until b.length) {
                buffer.append(a_t[i + j])
            }
            if (buffer.toString() == b) {
                count++
            }
        }

        return count
    }

    class EndBean {
        var status: Int = 0
        var downTime: String = ""
        var listOpdata: Any? = null
        var message: String = ""
        var list2: Any? = null
        var list: Any? = null
    }
}